package com.cms.edm.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cms.common.utils.R;
import com.cms.edm.dao.CourseDao;
import com.cms.edm.dao.TeacherDao;
import com.cms.edm.dao.TemplateDao;
import com.cms.edm.entity.CourseEntity;
import com.cms.edm.entity.TeacherEntity;
import com.cms.edm.entity.TemplateEntity;
import com.cms.edm.entity.vo.ResultOptionInVo;
import com.cms.edm.entity.vo.ResultOptionOutVo;
import com.cms.edm.entity.vo.ResultVo;
import com.cms.edm.feign.StuFeign;
import com.cms.edm.to.ClassTo;
import com.cms.edm.to.StudentDetailTo;
import com.cms.edm.to.StudentTo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cms.common.utils.PageUtils;
import com.cms.common.utils.Query;

import com.cms.edm.dao.ResultDao;
import com.cms.edm.entity.ResultEntity;
import com.cms.edm.service.ResultService;

import javax.annotation.Resource;


@Service("resultService")
public class ResultServiceImpl extends ServiceImpl<ResultDao, ResultEntity> implements ResultService {

    @Autowired
    private StuFeign stuFeign;

    @Resource
    private TemplateDao templateDao;

    @Resource
    private CourseDao courseDao;

    @Resource
    private TeacherDao teacherDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String key = (String) params.get("key");
        QueryWrapper<ResultEntity> wrapper = new QueryWrapper<>();
        if(!StringUtils.isEmpty(key)){
            wrapper.like("id", key);
        }
        IPage<ResultEntity> page = this.page(
                new Query<ResultEntity>().getPage(params),
                wrapper
        );

        List<ResultEntity> records = page.getRecords();
        List<ResultVo> collect = records.stream().map(item -> {
            ResultVo resultVo = new ResultVo();
            BeanUtils.copyProperties(item, resultVo);
            R r = stuFeign.studentInfo(item.getStudentId());
            if(r.getCode() == 0){
                StudentTo student = r.getData("student", new TypeReference<StudentTo>() {
                });
                resultVo.setStudentName(student.getName());
            }

            CourseEntity courseEntity = courseDao.selectById(item.getCourseId());
            resultVo.setCourseName(courseEntity.getName());
            return resultVo;
        }).collect(Collectors.toList());

        IPage<ResultVo> resultPage = new Page<>();
        resultPage.setTotal(page.getTotal());
        resultPage.setSize(page.getSize());
        resultPage.setPages(page.getPages());
        resultPage.setCurrent(page.getCurrent());
        resultPage.setRecords(collect);

        return new PageUtils(resultPage);
    }

    @Override
    public void setResultByTemplate(Long templateId, Long classId) {
        R r = stuFeign.infoByClassId(classId);
        List<StudentTo> students = null;
        if(r.getCode() == 0){
            students = r.getData("students", new TypeReference<List<StudentTo>>() {
            });
        }

        TemplateEntity templateEntity = templateDao.selectById(templateId);

        if(students != null && templateEntity != null){
            for (StudentTo student : students) {
                for (String s : templateEntity.getCourses().split(",")) {
                    ResultEntity resultEntity = new ResultEntity();
                    resultEntity.setCourseId(Long.parseLong(s));
                    resultEntity.setGrade(templateEntity.getGrade());
                    resultEntity.setStudentId(student.getId());
                    baseMapper.insert(resultEntity);
                }

            }
        }
    }

    @Override
    public List<ResultVo> selectAllCourseByStudentId(Long studentId) {
        List<ResultEntity> resultEntities = baseMapper.selectList(new QueryWrapper<ResultEntity>().eq("student_id", studentId));
        List<ResultVo> collect = resultEntities.stream().map(result -> {
            ResultVo resultVo = new ResultVo();
            BeanUtils.copyProperties(result, resultVo);
            CourseEntity courseEntity = courseDao.selectById(result.getCourseId());
            TeacherEntity teacherEntity = teacherDao.selectById(courseEntity.getTeacherId());
            resultVo.setCourseName(courseEntity.getName());
            resultVo.setTeacherName(teacherEntity.getName());

            return resultVo;
        }).collect(Collectors.toList());
        return collect;
    }

    @Override
    public List<ResultOptionOutVo> resultByTeacherId(ResultOptionInVo option) {
        List<StudentDetailTo> studentDetailTos = null;
        R r = stuFeign.selectStudentInfoByClassId(option.getClassId(), option.getStudentName());
        if(r.getCode() == 0){
            studentDetailTos = r.getData("studentDetailTos", new TypeReference<List<StudentDetailTo>>(){});
        }
        List<Long> studentIds = null;
        if(studentDetailTos != null && studentDetailTos.size() > 0){
            studentIds = studentDetailTos.stream().map(StudentDetailTo::getId).collect(Collectors.toList());
            List<ResultOptionOutVo> outVos = baseMapper.selectInfoByOptions(option.getTeacherId(), option.getIsNull(), studentIds);
            List<StudentDetailTo> finalStudentDetailTos = studentDetailTos;
            List<ResultOptionOutVo> result = outVos.stream().map(item -> {
                if (finalStudentDetailTos != null) {
                    for (StudentDetailTo studentDetailTo : finalStudentDetailTos) {
                        if (item.getStudentId() == studentDetailTo.getId()) {
                            item.setClassName(studentDetailTo.getClassName());
                            item.setStudentName(studentDetailTo.getStudentName());
                            break;
                        }
                    }
                }
                return item;
            }).collect(Collectors.toList());

            return result;
        }
        return new ArrayList<>();


    }

    @Override
    public List<ClassTo> classInfoByTeacherId(Long teacherId) {
        List<CourseEntity> courseEntities = courseDao.selectList(new QueryWrapper<CourseEntity>().eq("teacher_id", teacherId));
        List<Long> courseIds = courseEntities.stream().map(item -> item.getId()).collect(Collectors.toList());
        QueryWrapper<ResultEntity> wrapper = new QueryWrapper<>();
        wrapper.in("course_id", courseIds);
        List<ResultEntity> resultEntities = baseMapper.selectList(wrapper);
        List<Long> studentIds = resultEntities.stream().map(item -> item.getStudentId()).collect(Collectors.toList());
        R r = stuFeign.selectClassInfoByStudentIds(studentIds);
        List<ClassTo> classEntities = null;
        if(r.getCode() == 0){
            classEntities = r.getData("classEntities", new TypeReference<List<ClassTo>>() {
            });
        }
        return classEntities;
    }

}